package com.kite.ossServer;

import android.util.Log;
import android.webkit.JavascriptInterface;
import org.json.JSONObject;
import java.io.*;

public class rootNode {
    public File rootFile;
    public long filesize;
    public int hashId;
    public Node NodeTree;

    public rootNode(File rootFile) {
        this.rootFile = rootFile;
        this.filesize = rootFile.length();
        this.hashId = rootFile.hashCode();
        try {
            String readResult = FileAble.readTextFromFile(rootFile.getAbsolutePath());
            JSONObject readResponse = new JSONObject(readResult);

            if (readResponse.getBoolean("success")) {
                String jsondata = readResponse.getString("data");
                Node rootNode = new Node("ROOT_NODE");
                String parseResult = rootNode.parseJSONFromArray(jsondata, "ROOT_NODE");
                JSONObject parseResponse = new JSONObject(parseResult);

                if (parseResponse.getBoolean("success")) {
                    // 解析成功，使用解析后的节点
                    this.NodeTree = new Node("ROOT_NODE"); // 简化处理
                } else {
                    // 解析失败，创建空的根节点
                    android.util.Log.w("rootNode", "JSON解析失败: " + parseResponse.getString("error"));
                    this.NodeTree = new Node("ROOT_NODE");
                }
            } else {
                // 文件不存在或读取失败，创建空的根节点
                android.util.Log.w("rootNode", "读取根节点文件失败: " + readResponse.getString("error"));
                this.NodeTree = new Node("ROOT_NODE");
            }
        } catch (Exception e) {
            // 不抛出异常，而是记录错误并创建空的根节点
            android.util.Log.e("rootNode", "初始化根节点失败", e);
            this.NodeTree = new Node("ROOT_NODE");
        }
    }

    // 初始化根节点 - 重构版本，返回JSON响应而不是抛出异常
    @JavascriptInterface
    public static String initRoot(String filename) {
        try {
            if (filename == null || filename.trim().isEmpty()) {
                return createErrorResponse("文件名不能为空");
            }

            // 使用应用的内部存储目录而不是根目录
            File temp = new File("/data/data/com.kite.music/files", filename + ".json");

            if (!temp.exists()) {
                String createResult = FileAble.createFile("internal", filename, ".json");
                JSONObject createResponse = new JSONObject(createResult);

                if (!createResponse.getBoolean("success")) {
                    return createErrorResponse("创建根节点文件失败: " + createResponse.getString("error"));
                }

                temp = new File(createResponse.getString("data"));

                // 写入空的JSON对象
                String writeResult = FileAble.writeTextToFile(temp.getAbsolutePath(), "{}");
                JSONObject writeResponse = new JSONObject(writeResult);

                if (!writeResponse.getBoolean("success")) {
                    return createErrorResponse("写入根节点文件失败: " + writeResponse.getString("error"));
                }
            }

            // 创建rootNode实例（内部处理异常）
            rootNode root = new rootNode(temp);

            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("filePath", temp.getAbsolutePath());
            result.put("fileSize", temp.length());
            result.put("nodeCount", root.NodeTree != null ? root.NodeTree.nodeLength() : 0);

            return result.toString();

        } catch (Exception e) {
            return createErrorResponse("初始化根节点失败: " + e.getMessage());
        }
    }

    // 获取节点树信息
    @JavascriptInterface
    public String getNodeTreeInfo() {
        try {
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("filePath", rootFile.getAbsolutePath());
            result.put("fileSize", filesize);
            result.put("hashId", hashId);

            if (NodeTree != null) {
                result.put("nodeName", NodeTree.getNodeN());
                result.put("tropCount", NodeTree.TropLength());
                result.put("childCount", NodeTree.nodeLength());
            } else {
                result.put("nodeName", "ROOT_NODE");
                result.put("tropCount", 0);
                result.put("childCount", 0);
            }

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("获取节点树信息失败: " + e.getMessage());
        }
    }

    // 获取节点树
    @JavascriptInterface
    public String getNodeTree() {
        try {
            if (NodeTree == null) {
                return createErrorResponse("节点树未初始化");
            }
            String jsonString = NodeTree.toJSON();
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("jsonData", jsonString);
            result.put("nodeCount", NodeTree.nodeLength());
            result.put("tropCount", NodeTree.TropLength());

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("获取节点树失败: " + e.getMessage());
        }
    }

    // 获取文件信息
    @JavascriptInterface
    public String getFileInfo() {
        try {
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("filePath", rootFile.getAbsolutePath());
            result.put("fileSize", filesize);
            result.put("hashId", hashId);
            result.put("exists", rootFile.exists());
            result.put("canRead", rootFile.canRead());
            result.put("canWrite", rootFile.canWrite());
            result.put("lastModified", rootFile.lastModified());

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("获取文件信息失败: " + e.getMessage());
        }
    }

    // ============ 辅助方法 ============

    private static String createErrorResponse(String error) {
        try {
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("error", error);
            response.put("timestamp", System.currentTimeMillis());
            return response.toString();
        } catch (Exception e) {
            return "{\"success\":false,\"error\":\"响应创建失败\"}";
        }
    }

    public File getNTFill() {
        //TODO 返回文件
        return new File("xxx");
    }
}
